import { useEffect, useRef, useState } from 'react'
import { Overlay } from 'react-vant'

export default function useCaptchaBox(props: {
  onSuccess: (res: string) => void
}) {
  const [visible, setVisible] = useState<boolean>(false)

  useEffect(() => {
    if (visible)
      init()
  }, [visible])

  function init() {
    const config = {
      requestCaptchaDataUrl: '/api/contac/ka-moji/captch',
      validCaptchaUrl: '/api/contac/ka-moji/valid',
      bindEl: '#captcha-box',
      validSuccess: (res: any, c: any, tac: any) => {
        tac.destroyWindow()
        setVisible(false)
        props.onSuccess(res)
      },
      validFail: (res: any, c: any, tac: any) => {
        tac.reloadCaptcha()
      },
      btnRefreshFun: (el: any, tac: any) => {
        tac.reloadCaptcha()
      },
      btnCloseFun: (el: any, tac: any) => {
        setVisible(false)
        tac.destroyWindow()
      },
    }

    window.initTAC('./tac', config, {
      logoUrl: null,
    }).then((tac: any) => {
      tac.init() // 调用init则显示验证码
    })
  }

  function renderNode() {
    return (
      <Overlay visible={visible} zIndex={9999} className="flex justify-center pt-[200px] ">
        <div id="captcha-box"></div>
      </Overlay>
    )
  }

  function open() {
    setVisible(true)
  }

  return {
    renderNode,
    open,
  }
}
